package com.db.controller;

import com.db.entity.Person;
import com.db.service.PersonService;
import com.db.service.impl.PersonServiceImpl;
import com.db.util.FileUploadUitl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@WebServlet("/addPerson")
public class AddPersonServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            Map<String,String>map = FileUploadUitl.upload(request);
                //String name = item.getName();//如果此项表示文件，则name为文件名否则为null
                //String name =item.getFieldName();//如果此项是普通表单项。则name为表单参数的key
                //String value = item.getString();//获取表单项中的value


            String name = map.get("personName");
            String birthday = map.get("birthday");
            String sex = map.get("sex");
            String mobile = map.get("mobile");
            String address = map.get("address");
            String fileName = map.get("fileName");

            //将字符串转换为日期。或将日期转换为有格式的字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(birthday);

        //将文件名.后缀名存储到face属性中，表示该用户的头像
        Integer userid =(Integer) request.getSession().getAttribute("userid");
        Person person = new Person(null,name,date,sex,mobile,address,fileName,userid);
        PersonService ps = new PersonServiceImpl();
        Person person1 = ps.retrievePersonByNameMobile(person,userid);
        if(person1 != null){


        }else{

            ps.addPerson(person);
            response.sendRedirect(request.getContextPath()+"/showPersons");
        }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
